<!--
@description ：任务定义
-->

<template>
  <div>
    <NormalForm pageTitle="" :operateForm="queryForm" :formList="formList" :enumOpt="enumOpt" @handleQuery="handleQuery" @handleReset="handleReset"></NormalForm>
    <div class="g-card">
      <div class="table-top">
        <div class="title">任务定义规则列表</div>
        <el-button type="primary" @click="setConfig" icon="el-icon-plus" size="mini" style="height: 36px!important;">
          新增任务定义规则
        </el-button>
      </div>
      <div style="padding: 0 20px 20px 20px">
        <el-table v-loading="loading" :data="tableList" style="width: 100%" height="475">
          <el-table-column type="index" width="55" align="center" label="序号" />
          <el-table-column label="规则名称" align="center" show-overflow-tooltip prop="ruleName" :min-width="160"></el-table-column>
          <el-table-column label="管理机构" align="center" prop="institution" show-overflow-tooltip :min-width="160" :formatter="institutionFormatter">
          </el-table-column>
          <el-table-column label="渠道" align="center" prop="branchtype" show-overflow-tooltip :formatter="branchTypeFormatter">
          </el-table-column>
          <el-table-column label="修改时间" align="center" prop="updateTime" show-overflow-tooltip :min-width="170">
            <template slot-scope="scope">{{ scope.row.updateTime ? scope.row.updateTime : '-' }}</template>
          </el-table-column>
          <el-table-column label="创建人" align="center" prop="createBy" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="修改人" align="center" prop="updateBy" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" :min-width="160" class-name="small-padding fixed-width">
            <template slot-scope="{ row }">
              <div class="option-span">
                <el-button size="mini" type="text" @click="handleDetail(row)">详情</el-button>
                <el-button size="mini" type="text" @click="handleEdit(row)">修改</el-button>
                <el-button size="mini" type="text" @click="handleDelete" style="color: rgb(226, 55, 55)!important">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <NormalPagination :currentPage="queryForm.pageNum" :pageSize="queryForm.pageSize" :total="total" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"></NormalPagination>
      </div>
    </div>

    <el-drawer
      title="任务定义规则配置"
      :visible.sync="drawer"
      :direction="direction"
      :size="'60%'"
      :wrapper-closable="false"
      :before-close="handleClose">
      <div v-if="!createdSuccess">
      <el-form label-suffix=":" label-position="right" label-width="120px" ref="configForm" :model="configForm" :rules="configRules" :disabled="configFormDisabled">
        <el-form-item prop="ruleName" label="规则名称">
          <el-input v-model="configForm.ruleName" placeholder="请输入" size="small" clearable style="width: 60%;"></el-input>
        </el-form-item>
        <el-form-item prop="screen" label="筛选方式">
          <el-radio-group v-model="configForm.screen">
            <el-radio v-for="item in screeningList" :key="item.dictValue" :label="item.dictValue">{{ item.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="configForm.screen != 2" prop="institution" label="管理机构">
          <el-select v-model="configForm.institution" placeholder="请选择" clearable filterable style="width: 60%;">
            <el-option v-for="item in enumOpt.institutionList" :key="item.dictValue" :value="item.dictValue" :label="item.dictLabel"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="configForm.screen != 2" prop="branchtype" label="渠道">
          <el-select v-model="configForm.branchtype" placeholder="请选择" clearable filterable style="width: 60%;">
            <el-option v-for="item in enumOpt.branchtypeList" :key="item.dictValue" :value="item.dictValue" :label="item.dictLabel"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="configForm.screen == 2" prop="branchtype" label="上传清单">
      <el-upload
        class="upload-demo"
        :show-file-list="false"
        drag
        action
        :before-upload="uploadFile"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          <div v-for="(item, index) in fileList" :key="index" style="width: 350px">
            <div
              @mouseenter="iconShow = false"
              @mouseleave="iconShow = true"
              style="width: 350px; margin-bottom: 5px"
            >
              {{ item.name }}
              <i
                v-show="iconShow"
                class="el-icon-circle-check"
                style="color: greenyellow; float: right"
              ></i>
              <i
                @click="deleteText"
                v-show="!iconShow"
                class="el-icon-close"
                style="float: right"
              ></i>
            </div>
          </div>
          <!-- 支持Word，excel，ppt，pdf格式的文件 -->
        </div>
      </el-upload>
        </el-form-item>
        <el-form-item label="任务类型" prop="taskType">
          <el-checkbox-group v-model="configForm.taskType" style="display: flex;flex-direction: column">
            <el-checkbox v-for="item in taskTypeList" :label="item.dictValue" :key="item.dictValue">
              <span style="color: #606266!important;width: 90px;display: inline-block">{{ item.dictLabel }}</span><span style="color: rgb(67, 140, 255)!important;">({{ item.remark }})</span></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="是否触发提醒">
          <el-switch v-model="configForm.isWarn" active-color="#082aff" inactive-color="#DCDFE6"/>
        </el-form-item>
        <div v-if="configForm.isWarn">
          <el-form-item label="">
            <el-input v-model="warnMsg" :rows="4" maxlength="500"
                      placeholder="验证语最大长度为500个汉字，用作请求添加好友的话术，支持文字、数字、特殊字符等"
                      show-word-limit
                      style="width: 80%;"
                      disabled
                      type="textarea">
            </el-input>
          </el-form-item>
          <div style="margin-left: 132px; color: rgb(247, 0, 0)">提醒内容为提前设定好的模版，仅作参考，无法更改！</div>
          <el-form-item label="提醒方式" prop="warnType">
            <el-checkbox-group v-model="configForm.warnType">
              <el-checkbox v-for="item in reminderTypeList" :key="item.dictValue" :label="item.dictValue"
                           name="warnType">
                {{ item.dictLabel }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </div>
      </el-form>
      <div class="drawer-fromBtn">
        <el-button type="info" icon="el-icon-refresh-right" plain @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" :disabled="configFormDisabled">保存并提交</el-button>
      </div>
      </div>
      <div v-else class="createSuccessInfo">
        <img src="../../../assets/renewal/createSuccess.png" alt=""/>
        <div style="font-size: 14px;color: rgb(29, 29, 29);margin: 6px 0 12px 0">创建成功后的规则次日生效，相关机构和渠道的系统用户的任务中心会产生对应的菜单。</div>
        <div style="font-size: 14px;color: rgb(165, 165, 165);">{{ countDown }}秒后回到<a @click="toList">任务定义列表</a></div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { uploadFile } from '@/api/communityOperating/fileManage'

export default {
  name: "taskDefinition", //任务定义
  props:{

  },
  components:{

  },
  data(){
    return{
      fileList:[],
      iconShow:false,
       queryForm: {
          ruleName: '',
         institution: '',
         branchtype: '',
         pageNum: 1,
         pageSize: 20,
       },
      formList: [
        {
          label: '规则名称',
          defaultNoLabel: true,
          formLabel: true,
          value: '',
          prop: 'ruleName',
          type: 'INPUT',
          emunName: '',
          xs: 24,
          ls: 12,
          md: 10,
          lg: 8,
          xl: 6,
        },
        {
          label: '管理机构',
          defaultNoLabel: true,
          formLabel: true,
          value: '',
          prop: 'institution',
          type: 'SELECT',
          emunName: 'institutionList',
          xs: 24,
          ls: 12,
          md: 10,
          lg: 8,
          xl: 6,
        },
        {
          label: '渠道',
          defaultNoLabel: true,
          formLabel: true,
          value: '',
          prop: 'branchtype',
          type: 'SELECT',
          emunName: 'branchtypeList',
          xs: 24,
          ls: 12,
          md: 10,
          lg: 8,
          xl: 6,
        },
      ],
      enumOpt: {
        institutionList: [],
        branchtypeList: [],
      },

      tableList: [{}],
      loading: false,
      total: 0,

      drawer: false,
      direction: 'rtl',

      configForm: {
        ruleName: '',
        screen: '',
        institution: '',
        branchtype: '',
        taskType: [],
        isWarn: false,
        warnType: [],
      },
      warnMsg: '您名下今日新生成了<任务合计数值>条<任务类型>，请及时至任务中心查看！',
      configRules: {
        ruleName:  { required: true, message: '请输入规则名称', trigger: ['blur', 'change'] },
        screen: { required: true, message: '请选择筛选方式', trigger: ['blur', 'change'] },
        institution:{ required: true, message: '请选择管理机构', trigger: ['blur', 'change'] },
        branchtype: { required: true, message: '请选择渠道', trigger: ['blur', 'change'] },
        taskType: { required: true, message: '请选择任务类型', trigger: ['blur', 'change'] },
      },
      configFormDisabled: false,

      screeningList: [],
      taskTypeList: [],
      reminderTypeList: [],

      createdSuccess: false,
      countDown: 0,
      interval: null,
    }
  },
  watch:{
      'countDown': {
        handler(val,old){
          if(val <= 0) {
            this.drawer = false
            clearInterval(this.interval)
            this.handleQuery()
          }
        }
      }
  },
  methods:{
    async uploadFile(file) {
      console.log(file)
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('您上传的文件超过10M!')
      } else {
        const formData = new FormData()
        formData.append('file', file)
        const { data } = await uploadFile(formData)
        this.configForm.fileName = data.fileName
        this.configForm.fileUrl = data.url
        this.fileList = [
          {
            name: data.fileName,
            url: data.url
          }
        ]
      }
    },
    deleteText() {
      this.fileList = []
      this.iconShow = true
    },
    getDict(){
      this.getDicts("sys_renewal_channel").then((res) => {
        if (res.code === 200) {
          this.enumOpt.branchtypeList = res.data
        }
      });
      this.getDicts("sys_renewal_manage_com").then((res) => {
        if (res.code === 200) {
          this.enumOpt.institutionList = res.data
        }
      });
      this.getDicts("sys_renewal_definition_screening").then((res) => {
        if (res.code === 200) {
          this.screeningList = res.data
        }
      });
      this.getDicts("sys_renewal_definition_task_type").then((res) => {
        if (res.code === 200) {
          this.taskTypeList = res.data
        }
      });
      this.getDicts("sys_renewal_definition_reminder_type").then((res) => {
        if (res.code === 200) {
          this.reminderTypeList = res.data
        }
      });
    },
    institutionFormatter(row){
      return this.selectDictLabel(this.enumOpt.institutionList, row.institution);
    },
    branchTypeFormatter(row){
      return this.selectDictLabel(this.enumOpt.branchtypeList, row.branchtype);
    },
    handleQuery(){
      this.queryForm.pageNum = 1
      this.getListFn()
    },
    handleReset(){
      this.queryForm = {
        ruleName: '',
        institution: '',
        branchtype: '',
        pageNum: 1,
        pageSize: 20,
      }
      this.getListFn()
    },
    getListFn(){
      let obj = {
        ...this.queryForm
      }
      this.loading = true
      this.tableList = []
      this.api.getTaskConfigurationList(obj).then(res => {
        console.log('res::::', res)
        this.loading = false
        this.tableList = res.rows || []
        this.total = +res.total || 0
      }).catch(() => {
        this.loading = false
      })
    },
    handleCurrentChange(val){
       this.queryForm.pageNum = val
      this.getListFn()
    },
    handleSizeChange(val){
       this.queryForm.pageNum = 1
      this.queryForm.pageSize = val
      this.getListFn()
    },
    handleDelete(row){
      this.$confirm('此操作将删除此条信息, 是否继续?', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        console.log('taskId::::', row.taskId)
        this.api.deleteTaskConfiguration({taskId: row.taskId}).then(res => {
          if(res.code == 200){
            this.$message.success('删除成功')
            this.handleQuery()
          }
        })
      }).catch(() => {})
    },
    // 新增服务计划
    setConfig(){
      this.drawer = true
      this.configForm = {
        ruleName: '',
        screen: '',
        institution: '',
        branchtype: '',
        taskType: [],
        isWarn: false,
        warnType: [],
      }
      this.resetForm('configForm')
      this.createdSuccess = false
      this.configFormDisabled = false
    },

    handleEdit(row){
       this.api.queryTaskConfigurationDetail({taskId: row.taskId}).then(res => {
         if(res.code == 200){
           this.drawer = true
           this.configForm = {
             ...res.data,
             taskType: res.data.taskType ? res.data.taskType.split(',') : [],
             isWarn: res.data.isWarn == '1' ? true : false,
             warnType: res.data.warnType ? res.data.warnType.split(',') : [],
           }
           this.createdSuccess = false
           this.configFormDisabled = false
         }
       })
    },

    handleDetail(row){
      this.api.queryTaskConfigurationDetail({taskId: row.taskId}).then(res => {
        if(res.code == 200){
          this.drawer = true
          this.configForm = {
            ...res.data,
            taskType: res.data.taskType ? res.data.taskType.split(',') : [],
            isWarn: +res.data.isWarn == '1' ? true : false,
            warnType: res.data.warnType ? res.data.warnType.split(',') : [],
          }
          this.createdSuccess = false
          this.configFormDisabled = true
        }
      })
    },

    // 关闭抽屉
    handleClose(){
       this.drawer = false
       this.resetForm('configForm')
    },
    handleCancel(){
      this.drawer = false
      this.resetForm('configForm')
    },
    handleSubmit(){
      if(this.configFormDisabled) return
      this.$refs.configForm.validate(valid => {
        if(valid){
          let obj = {
            ...this.configForm,
            isWarn: true ? '1' : '0',
            taskType: this.configForm.taskType.toString(),
            warnType: this.configForm.warnType && this.configForm.warnType.length > 0 ? this.configForm.warnType.toString() : '',
          }
          if(this.configForm.taskId){
            this.api.editTaskConfiguration(obj).then(res => {
              if(res.code == 200){
                this.createdSuccess = true
                this.countDown = 10
                this.interval = window.setInterval(() => {
                  this.countDown--;
                },1000)
              }
            })
          }else{
            this.api.addTaskConfiguration(obj).then(res => {
              if(res.code == 200){
                this.createdSuccess = true
                this.countDown = 10
                this.interval = window.setInterval(() => {
                  this.countDown--;
                },1000)
              }
            })
          }
        }
      })
    },

    // 回到任务列表
    toList(){
      clearInterval(this.interval)
      this.drawer = false
      this.handleQuery()
    },
  },
  mounted() {
    this.getDict()
    this.handleQuery()
  },
  created() {
  },
}

</script>

<style lang="scss" scoped>
@import "../../../styles/base.scss";
.header-btn {
  @include headerBtn;
}

.wrap {
  @include titleWrap;
  padding-top: 16px;
  padding-left: 20px;
}

.img {
  position: relative;
  width: 148px;
  height: 148px;
  margin-right: 10px;

  img {
    height: 100%;
  }

  i {
    position: absolute;
    top: -5px;
    right: -5px;
    z-index: 10;
  }
}

.upload {
  display: flex;
}

.table-top {
  padding: 20px;
  height: 72px;
  border-bottom: 1px dashed #d9d9d9;
  margin-bottom: 12px;
  //line-height: 32px;
  display: flex;
  justify-content: space-between;
  .title{
    font-size: 20px;
    line-height: 32px;
  }
}

.drawer-fromBtn{
  display: flex;
  justify-content: end;
  padding: 16px 32px 0 0;
}

::v-deep{
  .el-drawer__header{
    margin-bottom: 18px;
    padding: 20px;
    padding-bottom: 20px;
    border-bottom: 1px dashed #d9d9d9;
    font-size: 20px;
    color: #000;
  }
  .el-drawer__body{
    padding-left: 16px;
  }
}

::v-deep{
  a{
    text-decoration: underline;
    cursor: pointer;
  }
}

.createSuccessInfo{
    display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 10%;
  img{
    height: 260px;
  }
}
</style>
